<?php
function cr_define($source){
    if (is_string($source)){
        $source=include $source;
    }
    
    if (!is_array($source))
        return false;
    foreach ($source as $sKey=>$sVal){
        if (is_bool($sVal) || is_string($sVal) || is_numeric($sVal) || is_null($sVal))
             define(strtoupper($sKey), $sVal);
    }
}


/*
 * memcache 现在只能有单台服务器
 * */
function & cache_server(){
    import('cr.libraries.cache');
    static $CS=null;
    if ($CS===null){
        switch (CACHE_SERVER){
            case 'memcached':
                list($host,$port)=explode(':', CACHE_MEMCACHED);
                $CS=new MemcacheServer(array(
                       'host'=>$host,
                       'port'=>$port
                    ));
                break;
           default:
               #TODO 还能完善 用文件缓存
               break;
        }
    }
    return $CS;
}

function import(){
    $c=func_get_args();
    if (empty($c))
        return;
    $code='$project_path="'.rtrim(CR_BASE,'/').'/";'.
          'strpos($item,"cr.")===false && $project_path="'.rtrim(APP_BASE,'/').'/";'.
          '$item=str_replace(array(\'cr\',\'@\',\'.\'),array(\'\',\'\',\'/\'),$item);'.
          '$item=ltrim($item,"/");'.
          'try{'.
          'if(!include_once($project_path.$item.\'.php\'))'.
          '    throw new Exception("文件不存在");'.
          '}catch(Exception $e){echo "加载文件失败：".$item.\'.php\'.$e->getMessage();}'.
          'APP_DEBUG && Debug::addMsg(\'<b>\'.$item.\'.php</b>文件\',1);';
    return array_walk($c, create_function('$item,$key', $code));
}

/*
 * @param string $name 模型名
 * @param array  $params  参数
 * @param bool   $is_new  是否新建
 * @return object
 * */
function & D($name='',$params=array(),$is_new=false){
    static $mod=array();
    $mod_hash=md5($name.var_export($params,true));
    if ($is_new || !isset($mod[$mod_hash])){
        $mod_file=APP_INC.'model/'.strtolower($name).'.php';
        if (file_exists($mod_file)){
            import('cr.libraries.model');
            include_once $mod_file;
            $class_name=ucfirst($name);
            $mod[$mod_hash]=new $class_name($params);
        }else{
            include_once CR_BASE.'libraries/model.php';
            $mod[$mod_hash]=new Model();
        }
        
    }
    return $mod[$mod_hash];
}